<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" draggable>
    <el-form ref="formRef" :model="passwordForm" :rules="rules" label-width="100px" label-suffix=" :">
      <el-form-item label="新密码" prop="password">
        <el-input v-model="passwordForm.password" type="password" placeholder="请输入新密码" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input v-model="passwordForm.checkPass" type="password" placeholder="请再次输入新密码" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import { ref, reactive } from "vue";
import { LOGIN_URL } from "@/config";
import { logoutApi } from "@/api/modules/system/login";
import { editUserPassWordApi } from "@/api/modules/system/user";
import { encryptSM2 } from "@/utils/sm2Crypto";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";

/** 路由 */
const router = useRouter();
/** 用户信息 */
const userStore = useUserStore();

/** 表单实例 */
const formRef = ref<FormInstance>();

/**
 * 密码格式校验
 * @param rule
 * @param value
 * @param callback
 */
const validatePass = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    if (value.length < 6) {
      callback(new Error("密码长度不可小于6位"));
    } else {
      if (passwordForm.value.checkPass !== "") {
        formRef.value?.validateField("checkPass");
      }
      callback();
    }
  }
};

/**
 * 密码格式校验
 * @param rule
 * @param value
 * @param callback
 */
const validatePass2 = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== passwordForm.value.password) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }
};

const dialogVisible = ref(false);
const passwordForm = ref({
  password: "",
  checkPass: ""
});
/** 表单验证规则 */
const rules = reactive<FormRules>({
  password: [{ required: true, validator: validatePass, trigger: "blur" }],
  checkPass: [{ required: true, validator: validatePass2, trigger: "blur" }]
});
const openDialog = () => {
  dialogVisible.value = true;
};

/**
 * 提交表单
 *
 * 1. 校验表单
 * 2. 询问是否确认提交
 * 3. 表单数据处理
 * 4. 提交表单
 * 5. 提交结果处理
 * 6. 退出登录
 * 7. 异常处理
 */
const handleSubmit = () => {
  formRef.value
    // 1. 校验表单
    ?.validate()
    // 2. 询问是否确认提交
    .then(() => {
      return ElMessageBox.confirm("确认修改密码吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      });
    })
    .catch(() => {
      return Promise.reject(new Error("取消修改密码！"));
    })
    // 3. 表单数据处理
    .then(() => {
      return {
        id: userStore.userInfo!.userId,
        passWord: encryptSM2(passwordForm.value.password)
      };
    })
    // 4. 提交表单
    .then(params => {
      return editUserPassWordApi(params);
    })
    // 5. 提交结果处理
    .then(({ data }) => {
      if (data) {
        ElMessage.success({ message: "修改密码成功！" });
        dialogVisible.value = false;
        return logoutApi();
      } else {
        return Promise.reject(new Error("修改密码失败！"));
      }
    })
    // 6. 退出登录
    .then(() => {
      userStore.setToken("", "");
      router.replace(LOGIN_URL);
    })
    // 7. 异常处理
    .catch((error: Error) => {
      if (error.message) ElMessage.error({ message: `修改密码异常：${error.message}` });
      else ElMessage.error({ message: "请检查表单数据是否填写完整！" });
    });
};

defineExpose({ openDialog });
</script>
